﻿using System.Web.Mvc;

namespace Golf.WebUI.Models
{
    using Core;
    using DataLayer;

    public class PlayerBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Player player = base.BindModel(controllerContext, bindingContext) as Player;
            player.Gender = GetValue<Gender>(bindingContext, "Gender");
            player.County = new CountyRepository().Get(GetValue<int>(bindingContext, "County"));
            return player;
        }

        private T GetValue<T>(ModelBindingContext bindingContext, string key)
        {
            ValueProviderResult valueResult;
            bindingContext.ValueProvider.TryGetValue(key, out valueResult);
            bindingContext.ModelState.SetModelValue(key, valueResult);
            return (T)valueResult.ConvertTo(typeof(T));
        }
    }
}